#include "MainState.h"
#include "Application.h"
#include "Fonts.h"
#include <sfml/Graphics.hpp>

MainState::MainState()
{

	m_cNormal = sf::Color::White;
	m_cSelected = sf::Color::Yellow;
	m_cShadow = sf::Color::Color(50,50,50);

	sf::Font* font = Fonts::Istance()->GetFont("Consola");
	m_menu[0] = sf::Text("New Game", (*font), 26);
	m_menu[1] = sf::Text("Settings", (*font), 26);
	m_menu[2] = sf::Text("Credits", (*font), 26);
	m_menu[3] = sf::Text("Exit", (*font), 26);

	m_shadows[0] = sf::Text("New Game", (*font), 26);
	m_shadows[1] = sf::Text("Settings", (*font), 26);
	m_shadows[2] = sf::Text("Credits", (*font), 26);
	m_shadows[3] = sf::Text("Exit", (*font), 26);

	float maxWidth = 0.f;
	float maxHeight = 0.f;

	for (int i  = 0; i < Elements ; i++)
	{
		maxWidth = (m_menu[i].GetRect().Width>maxWidth) ? m_menu[i].GetRect().Width : maxWidth;
		maxHeight = (m_menu[i].GetRect().Height>maxHeight) ? m_menu[i].GetRect().Height : maxHeight;
	}

	m_pos = sf::Vector2f((Application::Istance()->Window()->GetWidth()*0.5f ) - (maxWidth*0.5f), 
							Application::Istance()->Window()->GetHeight()*0.5f - (maxHeight*0.5f*Elements));
	
	for (int i  = 0; i < Elements ; i++)
	{
		m_menu[i].SetPosition(sf::Vector2f(m_pos.x + ((maxWidth-m_menu[i].GetRect().Width)*0.5f) , 
											m_pos.y + maxHeight*i));
		m_shadows[i].SetPosition(sf::Vector2f(m_menu[i].GetPosition().x + 2.f, m_menu[i].GetPosition().y + 2.f));
		m_shadows[i].SetColor(m_cShadow);
	}

	m_selected = 0;
}

MainState::~MainState()
{
}

void MainState::OnDraw(sf::RenderWindow& renderWindow)
{
	renderWindow.SaveGLStates();
	
	for (int i  = 0; i < Elements ; i++)
	{
		renderWindow.Draw(m_shadows[i]);
		m_menu[i].SetColor( ( i == m_selected) ? m_cSelected : m_cNormal );
		renderWindow.Draw(m_menu[i]);
	}

	renderWindow.RestoreGLStates();
}

void MainState::OnIdle(const sf::Input& input)
{
	if( Application::Istance()->IsInputAvailable() ){
		if (input.IsKeyDown(sf::Key::Down) || input.GetJoystickAxis(0,sf::Joy::AxisY)>=50.f )
		{
			m_selected = (m_selected == Elements-1) ? 0 : m_selected + 1 ;
			Application::Istance()->PauseInput();
		}
		else if (input.IsKeyDown(sf::Key::Up) || input.GetJoystickAxis(0,sf::Joy::AxisY)<=-50.f )
		{
			m_selected = (m_selected == 0) ? Elements-1 : m_selected -1 ;
			Application::Istance()->PauseInput();
		}
	
		if (input.IsKeyDown(sf::Key::Return)		//Enter pressed
			|| input.IsJoystickButtonDown(0,2)		//'X' button
			|| input.IsJoystickButtonDown(0,11))	//'Start' Button
		{
			switch (m_selected)
			{
				case 0:
					Application::Istance()->SetState("Game");
					break;
				case 1:
					{
						Application::Istance()->SetState("SettingsMenu");
						Application::Istance()->PauseInput(0.5);
						break;
					}
				case 3:
					Application::Istance()->Exit();
					break;
				default:
					break;
			}

		}
	}

}
